package com.lagou.rpc.client;

import com.lagou.rpc.entity.RpcRequest;
import com.lagou.rpc.entity.RpcResponse;
import com.lagou.rpc.protocol.JSONSerializer;
import com.lagou.rpc.protocol.RpcDecoder;
import com.lagou.rpc.protocol.RpcEncoder;
import com.lagou.rpc.service.ResumeService;
import com.lagou.rpc.service.UserService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @see com.lagou.rpc.client.RpcClientHandler
 */
public class NettyClient {

    private volatile RpcClientHandler clientHandler;
    private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(16, 16,
            600L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(65536));

    public NettyClient() throws Exception {
        this.start();
    }

    /**
     * 创建一个代理类。
     * @param interfaceClass
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> T createProxy(Class interfaceClass) throws Exception {
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class<?>[]{interfaceClass},
                handler(interfaceClass));
    }

    InvocationHandler handler(Class interfaceClass) {
        return new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setClassName(lowerFirst(interfaceClass.getSimpleName()));
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameters(objects);

                RpcFuture future = clientHandler.sendRequest(rpcRequest);
                return future.get();
            }
        };
    }

    String lowerFirst(String name) {
        if (name == null) {
            return "";
        }
        char[] arr = name.toCharArray();
        arr[0] += 32;
        return new String(arr);
    }

    // 启动客户端netty
    public void start() throws Exception {
        this.clientHandler =  new RpcClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(
        65536, 0, 4, 0, 0));
                        pipeline.addLast(new RpcEncoder(new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(new JSONSerializer(), RpcResponse.class));
                        pipeline.addLast(clientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1",8848).sync();
    }


    public static void main(String[] args) throws Exception {
//        //new NettyClient();
        NettyClient client = new NettyClient();
        UserService userService = client.createProxy(UserService.class);
        System.out.println(userService.say("张三"));

        ResumeService resumeService = client.createProxy(ResumeService.class);
        System.out.println(resumeService.save("这是一条简历"));
    }


}
